package com.youboy.wechatapi.web.controller;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.type.JavaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.youboy.wechatapi.service.record.VisitService;
import com.youboy.wechatapi.utils.json.JacksonMapper;
import com.youboy.wechatapi.utils.wechat.WechatApi;

@Controller
public class HelpController {

	private Logger log = Logger.getLogger(HelpController.class);

	//微信用户授权获取用户信息接口
	@Value(value = "${api.oauth2.accesstoken}")
	private String api_oauth2_accesstoken;

	//微信接口开发者标识
	@Value(value = "${api.appid}")
	private String appid;
	@Value(value = "${api.secret}")
	private String secret;

	@Autowired
	private VisitService visitService;

	
	/**
	 * 微信方回调接口，前往绑定页面
	 * @param model
	 * @param code
	 * 				code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5
	 *            	分钟未被使用自动过期。
	 * @param state
	 * @return
	 */
	@RequestMapping(value = "/help/wechatCallBack", produces = { "text/html;charset=utf-8" })
	public String wechatCallBack(Model model, HttpSession session,
			@RequestParam(value = "code", required = false) String code,
			@RequestParam(value = "state") String state, 
			@RequestParam(value = "redirect_url") String redirect_url) {

		String openid = WechatApi.getOpenid(code);
		if(StringUtils.isBlank(openid)){
			log.error("[code:" + code + "] can't get openid !");
			return null;
		}
		
		try {
			visitService.saveVisitInfo(openid, redirect_url);
		} catch (Exception e) {
			log.error("[openid:" + openid + "][redirectUrl:" + redirect_url + "] save visitInfo error !", e);
		}
		
		if (redirect_url.contains("?")) {
			redirect_url += "&openid="+openid;
		} else {
			redirect_url += "?openid="+openid;
		}
		return "redirect:"+redirect_url;
	}
	
	@RequestMapping(value = "/help/callBack", produces = { "text/html;charset=utf-8" })
	public String callBack(Model model,
			@RequestParam(value = "openid") String openid,
			@RequestParam(value = "redirect_url") String redirect_url) {
		try {
			visitService.saveVisitInfo(openid, redirect_url);
		} catch (Exception e) {
			log.error("[openid:" + openid + "][redirectUrl:" + redirect_url + "] save visitInfo error !", e);
		}
		return "redirect:"+redirect_url;
	}

	@RequestMapping(value = "/help/userinfo", produces = { "text/html;charset=utf-8" })
	@ResponseBody
	public String showUserInfo(@RequestParam(value = "openid") String openid){
		String userInfoJson = null;
		try {
			userInfoJson = WechatApi.getUserInfo(openid);
		} catch (Exception e) {
			log.error("[openid:" + openid + "] get userinfo error !", e);
		}
		

		if(StringUtils.isBlank(userInfoJson) || userInfoJson.contains("errcode")){
			return null;
		}
		
		Map<String, Object> userInfoMap = null;
		
		try {
			JavaType type = JacksonMapper.getInstance().getTypeFactory()
					.constructMapType(Map.class, String.class, Object.class);
			userInfoMap = JacksonMapper.getInstance().readValue(userInfoJson, type);
		} catch (Exception e) {
			log.error("[openid:" + openid + "] getUserInfo by openid convert to map error !", e);
		}
		
		if (userInfoMap == null || userInfoMap.size() == 0) {
			log.error("[openid:" + openid + "] get userinfo from wechat error !");
			return null;
		}
	
		StringBuilder userStr = new StringBuilder();
		for (String key : userInfoMap.keySet()) {
			userStr.append("【").append(key).append("     :     ").append(userInfoMap.get(key)).append("】<br>\r\n");
		}
		
		return userStr.toString();
	}
}
